########################################################
###### Replication Code for Figure 4 and Table A7 ######
################## January 9th, 2025 ################### 
########################################################

### Script produces Figure 4 and Table A7 and saves them 
### in the `/tables` and `/figures` folder respectively

rm(list=ls())

# Load libraries
library(fixest)
library(modelsummary)
library(dplyr)
library(fixest)
library(ggplot2)
library(stringr)
library(MatchIt)
library(ebal)
library(hbal)

############ Figure 4: Effect of mentioning immigration among left- and right-leaning respondents ################

# load data
df <- readRDS("data/workfile.rds")
w <- readRDS("data/weighted_party_feeling.rds")

# summarise the two variables for outparty feeling/distance
df$out_feeling <- scale(df$mean_outparty_feeling) + scale(df$mean_close_num)

# join weights to main data
df <- df %>% left_join(w)

# specify control variables
control_variables <- c('high_pol_interest',
                       "high_edu", "medium_edu", "low_edu",  "dem_age",
                       "parfam_nat", "parfam_left", "parfam_con", "mean_close_num", "mean_outparty_feeling",
                       "coDE", "coFR", "coES", "coNL", "coUS", "coPL", 
                       "coGR", "coIT", "coSE", "d_affiliated", 
                       "high_income", "medium_income", "low_income")

# scale outcome variable
df$trust_in_opposing_parties <- scale(df$trust_in_opposing_parties)

# generate empty dataframe for balancing coefs
coef_df <- data.frame()

########## Select variables
df <- df %>% 
  select(open_immig, dem_female, dem_country_code, dem_education_level,
         dem_country_code, dem_rural, dem_age, lrscale, parfam_name,
         high_pol_interest, mean_close_num, d_affiliated,
         high_edu, medium_edu, low_edu, treated, mean_outparty_feeling, 
         political_interest_num, treated_econ, treated_culture, out_feeling,
         trust_in_opposing_parties, 
         low_income, medium_income, high_income) %>% 
  mutate(coDE = ifelse(dem_country_code == "DE", 1, 0), 
         coFR = ifelse(dem_country_code == "FR", 1, 0), 
         coNL = ifelse(dem_country_code == "NL", 1, 0),
         coUS = ifelse(dem_country_code == "US", 1, 0),
         coPL = ifelse(dem_country_code == "PL", 1, 0),
         coGR = ifelse(dem_country_code == "GR", 1, 0), 
         coIT = ifelse(dem_country_code == "IT", 1, 0), 
         coSE = ifelse(dem_country_code == "SE", 1, 0), 
         coGB = ifelse(dem_country_code == "GB", 1, 0), 
         coES = ifelse(dem_country_code == "ES", 1, 0), 
         parfam_liberal = ifelse(parfam_name == "Liberal parties", 1, 0), 
         parfam_other = ifelse(parfam_name == "Other parties", 1, 0), 
         parfam_eco = ifelse(parfam_name == "Ecological parties", 1, 0), 
         parfam_nat = ifelse(parfam_name == "Nationalist parties", 1, 0), 
         parfam_left = ifelse(parfam_name == "Socialist/left parties", 1, 0), 
         parfam_cd = ifelse(parfam_name == "Christian democratic parties", 1, 0), 
         parfam_nonvoters = ifelse(parfam_name == "Non-voters", 1, 0), 
         parfam_sd = ifelse(parfam_name == "Social democratic parties", 1, 0), 
         parfam_con = ifelse(parfam_name == "Conservative parties", 1, 0), 
         parfam_ethnic = ifelse(parfam_name == "Ethnic and regional parties", 1, 0),
         parfam_spec = ifelse(parfam_name == "Special issue party", 1, 0),)

##### Immigration - Culturalcondition Left
nomiss <- df %>% 
  filter((open_immig == 0 & treated_culture == 1) | treated == 0 & lrscale < 5) %>% 
  .[complete.cases(.), ]

hbal.out <- hbal(Treat = 'treated', 
                 X = control_variables,  
                 Y = 'trust_in_opposing_parties',  data = nomiss)
m1 = att(hbal.out, dr = FALSE)
discussion_culture_left <- m1

temp <- data.frame(coef = c(m1$Estimate[1]),
                   se = c(m1$`Std. Error`[1]), 
                   name = "Cultural condition",
                   var = "Trust", 
                   group = "Left-wing respondents")

coef_df <- rbind.data.frame(coef_df, temp)


##### Immigration - Culturalcondition Right
nomiss <- df %>% 
  filter((open_immig == 1 & treated_culture == 1) | treated == 0 & lrscale > 5) %>% 
  .[complete.cases(.), ]

hbal.out <- hbal(Treat = 'treated', 
                 X = control_variables,  
                 Y = 'trust_in_opposing_parties',  data = nomiss)
m1 = att(hbal.out, dr = FALSE)
discussion_culture_right <- m1

temp <- data.frame(coef = c(m1$Estimate[1]),
                   se = c(m1$`Std. Error`[1]),
                   name = "Cultural condition",
                   var = "Trust", 
                   group = "Right-wing respondents")

coef_df <- rbind.data.frame(coef_df, temp)


##### Immigration - Economiccondition Right
nomiss <- df %>% 
  filter((open_immig == 1 & treated_econ == 1) | treated == 0 & lrscale > 5) %>% 
  .[complete.cases(.), ]

hbal.out <- hbal(Treat = 'treated', 
                 X = control_variables,  
                 Y = 'trust_in_opposing_parties',  data = nomiss)
m1 = att(hbal.out, dr = FALSE)
discussion_econ_right <- m1

temp <- data.frame(coef = c(m1$Estimate[1]),
                   se = c(m1$`Std. Error`[1]),
                   name = "Economic condition",
                   var = "Trust", 
                   group = "Right-wing respondents")

coef_df <- rbind.data.frame(coef_df, temp)


##### Immigration - Economiccondition Left
nomiss <- df %>% 
  filter((open_immig == 1 & treated_econ == 1) | treated == 0 & lrscale < 5) %>% 
  .[complete.cases(.), ]

hbal.out <- hbal(Treat = 'treated', 
                 X = control_variables,  
                 Y = 'trust_in_opposing_parties',  data = nomiss)
m1 = att(hbal.out, dr = FALSE)
discussion_econ_left <- m1

temp <- data.frame(coef = c(m1$Estimate[1]),
                   se = c(m1$`Std. Error`[1]),
                   name = "Economic condition",
                   var = "Trust", 
                   group = "Left-wing respondents")

coef_df <- rbind.data.frame(coef_df, temp)


### Misc
pd <- position_dodge(0.5)

### Create Figure 4
regs <- ggplot(coef_df, aes(x = name,  y = coef,  color = group)) + 
  geom_point(position = pd, shape = 21, fill = 'white') + 
  geom_errorbar(aes( ymin = coef - se*1.959964, ymax = coef + se*1.959964), width = 0, position = pd) + 
  geom_errorbar(aes( ymin = coef - se*1.644854, ymax = coef + se*1.644854), width = 0, position = pd, linewidth = 1.2) + 
  geom_hline(yintercept = 0, color = "red", linetype = "dashed") +
  scale_colour_manual(values = c("black", "grey")) + 
  xlab("") + 
  ylab("Effect of discussing immigration on out-partisan trust") +
  coord_flip() +
  theme_bw() + 
  guides(color=guide_legend(title="")) + 
  theme(legend.position="bottom")

regs
ggsave("figures/Fig4_entropy_balancing_predictors_by_lr.pdf",
        height = 4, width = 6)

############ Table A7: Effect of mentioning immigration among left- and right-leaning respondents ################

### Bring in correct format in order to process table with modelsummary
discussion_econ_right$term <- rownames(discussion_econ_right)
discussion_econ_right$std.error <- discussion_econ_right$`Std. Error`
discussion_econ_right$p.value <- discussion_econ_right$`Pr(>|t|)`
discussion_econ_right$estimate <- discussion_econ_right$Estimate
rownames(discussion_econ_right) <- NULL

gl <- data.frame(
  Num.Obs. = discussion_econ_right$DF + 2)
discussion_econ_right <- list(
  tidy = discussion_econ_right[, 8:11],
  glance = gl)
class(discussion_econ_right) <- "modelsummary_list"
modelsummary(discussion_econ_right, stars = T)

### Bring in correct format in order to process table with modelsummary
discussion_econ_left$term <- rownames(discussion_econ_left)
discussion_econ_left$std.error <- discussion_econ_left$`Std. Error`
discussion_econ_left$p.value <- discussion_econ_left$`Pr(>|t|)`
discussion_econ_left$estimate <- discussion_econ_left$Estimate
rownames(discussion_econ_left) <- NULL

gl <- data.frame(
  Num.Obs. = discussion_econ_left$DF + 2)
discussion_econ_left <- list(
  tidy = discussion_econ_left[, 8:11],
  glance = gl)
class(discussion_econ_left) <- "modelsummary_list"
modelsummary(discussion_econ_left, stars = T)

### Bring in correct format in order to process table with modelsummary
discussion_culture_right$term <- rownames(discussion_culture_right)
discussion_culture_right$std.error <- discussion_culture_right$`Std. Error`
discussion_culture_right$p.value <- discussion_culture_right$`Pr(>|t|)`
discussion_culture_right$estimate <- discussion_culture_right$Estimate
rownames(discussion_culture_right) <- NULL

gl <- data.frame(
  Num.Obs. = discussion_culture_right$DF + 2)
discussion_culture_right <- list(
  tidy = discussion_culture_right[, 8:11],
  glance = gl)
class(discussion_culture_right) <- "modelsummary_list"
modelsummary(discussion_culture_right, stars = T)

### Bring in correct format in order to process table with modelsummary
discussion_culture_left$term <- rownames(discussion_culture_left)
discussion_culture_left$std.error <- discussion_culture_left$`Std. Error`
discussion_culture_left$p.value <- discussion_culture_left$`Pr(>|t|)`
discussion_culture_left$estimate <- discussion_culture_left$Estimate
rownames(discussion_culture_left) <- NULL

gl <- data.frame(
  Num.Obs. = discussion_culture_left$DF + 2)
discussion_culture_left <- list(
  tidy = discussion_culture_left[, 8:11],
  glance = gl)
class(discussion_culture_left) <- "modelsummary_list"
modelsummary(discussion_culture_left, stars = T)

### Generate table with modelsummary
modellist <- list(discussion_econ_right, discussion_econ_left, discussion_culture_right, discussion_culture_left)
names(modellist) <- c("Right-Econ", "Left-Econ", "Right-Cultural", "Left-Cultural")
modelsummary(modellist, stars = T)
m_sum <- modelsummary(modellist, stars = T,
                      statistic = c("std.error",
                                    "p = {p.value}"),
                      title = "Treatment effect on out-partisan trust",
                      gof_omit = "BIC|AIC|r2.within|r2.within.adjusted|rmse|std.error.type|se_type",
                      coef_rename = c("treated" = "Discussed immigration", 
                                      "mean_outparty_feeling" = "Average outpartisan feeling", 
                                      "high_pol_interest" = "High political interest"), 
                      output = "tables/TabA7.html")

